/*
 *  (C) Copyright 2008 Insula Tecnologia da Informacao Ltda.
 * 
 *  This file is part of Vulcano.
 *
 *  Vulcano is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Vulcano is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with Vulcano.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.openinsula.vulcano.orm.dao.query.hibernate;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.openinsula.vulcano.orm.dao.query.DaoQuery;
import org.openinsula.vulcano.orm.dao.query.DaoQueryVisitor;
import org.openinsula.vulcano.orm.dao.query.spec.Spec;
import org.openinsula.vulcano.orm.dao.query.spec.SpecVisitor;
import org.springframework.stereotype.Component;

@Component
public class HibernateDaoQueryTranslator {
	private final DaoQueryVisitor<String> hqlFromDaoQueryVisitor = new HqlFromDaoQueryVisitorImpl();
	private final SpecVisitor<String> hqlSpecVisitor = new HqlSpecVisitorImpl();
	private final DaoQueryVisitor<String> hqlOrderDaoQueryVisitor = new HqlOrderDaoQueryVisitorImpl();
	private final SpecVisitor<List<Object>> parameterSpecVisitor = new ParameterSpecVisitorImpl();
	
	/**
	 * Metodo que cria a String em HQL para a consulta no Dao.
	 * @param daoQuery A DaoQuery sendo executada.
	 * @return A string em HQL da DaoQuery.
	 */
	public String createHql(final DaoQuery daoQuery) {
    	StringBuilder sb = new StringBuilder();
    	
    	sb.append(daoQuery.accept(hqlFromDaoQueryVisitor));
    	
    	Spec spec = daoQuery.getSpec();
    	
    	if (spec != null) {
    		sb.append(spec.accept(hqlSpecVisitor));
    	}
    	
    	sb.append(daoQuery.accept(hqlOrderDaoQueryVisitor));

    	return sb.toString();
	}
	
	/**
	 * Metodo que seta as configuracoes da Query, tais como parametros
	 * da consulta, limite, primeiro resultado e lock. 
	 * @param query A Query do Hibernate a ser configurada.
	 * @param daoQuery A DaoQuery que contem os valores p/ configurar a Query.
	 */
	public void configureQuery(final Query query, final DaoQuery daoQuery) {
		List<Object> params = getSpecParameters(daoQuery.getSpec());
    		
    	for (int i = 0, j = params.size(); i < j; i++) {
    		query.setParameter(i, params.get(i));
    	}
    	
    	daoQuery.accept(new SetIntervalResultDaoQueryVisitorImpl(query));
    	daoQuery.accept(new SetLockDaoQueryVisitorImpl(query));
	}
	
	public List<Object> getSpecParameters(final Spec spec) {
		return spec == null ? new ArrayList<Object>() : spec.accept(parameterSpecVisitor); 
	}
}
